<?php
namespace App\Libs\Coupons;
use \App\Libs\DB\PailePdo;
use \App\Libs\Exception\RuntimeException;
use \App\Libs\Base\Constant;
class Couponslib extends \App\Libs\Base\AccessObject
{
	/**
	*	获取优惠券
	*/
	public static function getCoupons( $params ){
		$where = '';
		$params = array_merge( [ 'page'=>1 , 'size'=>10 ] , $params );
		//参数处理
		if( !empty( $params['uid'] ) ){
			$where .= " and uid = ".$params['uid'];
		}
		
		//limit
		$limit = " limit ".( ($params['page']-1)*$params['size'] ).','.$params['size'];
		
		//sql
		$sql = "SELECT my.*,coupons.title,coupons.full_price,coupons.price,coupons.type FROM t_paile_coupons_my my LEFT JOIN t_paile_coupons coupons ON my.cid = coupons.id WHERE coupons.is_show = 1 and coupons.label = 1 and my.status = {$params['status']} ".$where.$limit;
		$data = PailePdo::findAll($sql);
		//数据处理
		if(count($data) > 0 ){
			if($params['status'] == 0 ){
				$nowTime = date("Y-m-d H:i:s");
				$statusArr = [];
				//已过期的数据，修改状态
				foreach( $data as $k=>$v ){
					if( $v['end_time'] < $nowTime ){
						$statusArr[] = $v['id'];
						unset( $data[$k] );//已过期的，去除
					}
				}
				if( !empty( $statusArr ) ){
					$statusStr = implode( ',' , $statusArr );
					$conditions = array(
						'conditions' => ' id in(?)',
						'bind' => array($statusStr),
					);
					$res = PailePdo::update( 't_paile_coupons_my',  array("status"=>2) ,$conditions);   
				}
			}
			return $data;
		}else{
			return false;
		}
	}
	
	
	/**
	*	获取可用和不可用的优惠券
	*/
	public static function getCouponsZone( $uid ){
		$nowTime = date("Y-m-d H:i:s");
		$sql = "SELECT my.*,coupons.title,coupons.full_price,coupons.price,coupons.type FROM t_paile_coupons_my my LEFT JOIN t_paile_coupons coupons ON my.cid = coupons.id WHERE coupons.is_show = 1 and coupons.label = 1 and my.start_time <= '{$nowTime}' AND my.end_time >= '{$nowTime}' and my.uid = {$uid}";
		$data = PailePdo::findAll($sql);
		if(count($data) > 0 ){
				return $data;
		}else{
			return false;
		}
	}
}
